package org.zkdn.modules.wlpt.basicinfo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.collections4.CollectionUtils;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.zkdn.modules.wlpt.basicinfo.dto.CrossDTO;
import org.zkdn.modules.wlpt.basicinfo.entity.*;
import org.zkdn.modules.wlpt.basicinfo.entity.TCrossing;
import org.zkdn.modules.wlpt.basicinfo.enums.DictCodeEnums;
import org.zkdn.modules.wlpt.basicinfo.mapper.TCrossingMapper;
import org.zkdn.modules.wlpt.basicinfo.service.ITCrossingRefTagService;
import org.zkdn.modules.wlpt.basicinfo.service.ITCrossingService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.zkdn.modules.wlpt.basicinfo.service.ITRoadRefCrossService;
import org.zkdn.modules.wlpt.basicinfo.service.ITRoadService;
import org.zkdn.modules.wlpt.basicinfo.vo.CrossVO;
import org.zkdn.modules.wlpt.basicinfo.vo.RoadVO;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: t_crossing
 * @Author: jeecg-boot
 * @Date:   2025-06-18
 * @Version: V1.0
 */
@Service
public class TCrossingServiceImpl extends ServiceImpl<TCrossingMapper, TCrossing> implements ITCrossingService {

    @Autowired
    private TCrossingMapper crossingMapper;

    @Autowired
    private ITCrossingRefTagService crossRefTagService;

    @Autowired
    private ITRoadRefCrossService  roadRefCrossService;

    @Autowired
    private ITRoadService roadService;

    @Override
    public List<CrossVO> queryList(QueryWrapper queryWrapper) {
        List<CrossVO> list = crossingMapper.queryList(queryWrapper);
        list.forEach(record -> {
            String roadId = record.getRoadId();
            if (roadId != null) {
                List<String> roadIdlist = Arrays.stream(roadId.split(","))
                        .filter(s -> !s.isEmpty()) // 过滤空字符串
                        .collect(Collectors.toList());
                record.setRoadIds(roadIdlist);
            }
        });
        return list;
    }

    @Override
    public IPage<CrossVO> queryPageList(IPage<CrossVO> page, QueryWrapper queryWrapper) {
        IPage<CrossVO> pageList = crossingMapper.queryPageList(page, queryWrapper);
        pageList.getRecords().forEach(record -> {
            String roadId = record.getRoadId();
            if (roadId != null) {
                List<String> roadIdlist = Arrays.stream(roadId.split(","))
                        .filter(s -> !s.isEmpty()) // 过滤空字符串
                        .collect(Collectors.toList());
                record.setRoadIds(roadIdlist);
            }
        });
        return pageList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveByValidate(CrossDTO crossDTO) {
        QueryWrapper<TCrossing> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", crossDTO.getCode());
        List<TCrossing> exitsList = crossingMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(exitsList)) {
            return Result.error("路口编号'" + crossDTO.getCode() + "'已存在!" );
        }
        //处理道路ids
        List<String> roadIdList = crossDTO.getRoadIds();
        String roadIds = String.join(",", roadIdList);

        List<TRoad> roadList = roadService.list(new QueryWrapper<TRoad>().in("id", roadIdList));
        String roadName = roadList.stream()
                .map(road -> road.getRoadName())         // 提取每个TRoad对象的name属性
                .filter(Objects::nonNull)    // 过滤掉可能存在的null值
                .collect(Collectors.joining(",")); // 用逗号连接成字符串

        TCrossing crossing = new TCrossing();
        BeanUtils.copyProperties(crossDTO, crossing);
        crossing.setRoadId(roadIds);
        crossing.setRoadName(roadName);
        crossingMapper.insert(crossing);

        //处理路口和道路关系
//        String roadIds = crossing.getRoadId();
//        List<String> roadIdList = Arrays.asList(roadIds.split(","));
        if (CollectionUtils.isNotEmpty(roadIdList)) {
            // 创建TCrossingRefTag集合
            List<TRoadRefCross> refTagList = roadIdList.stream()
                    .map(roadId -> {
                        TRoadRefCross refCross = new TRoadRefCross();
                        refCross.setRoadId(roadId);
                        refCross.setCrossId(crossing.getId());
                        return refCross;
                    })
                    .collect(Collectors.toList());

            // 输出结果
//            refTagList.forEach(System.out::println);
            roadRefCrossService.saveBatch(refTagList);
        }

        //处理路口标签关系
        String tags = crossing.getCrossTag();
        List<String> tagList = Arrays.asList(tags.split(","));
        if (CollectionUtils.isNotEmpty(tagList)) {
            // 创建TCrossingRefTag集合
            List<TCrossingRefTag> refTagList = tagList.stream()
                    .map(tag -> {
                        TCrossingRefTag refTag = new TCrossingRefTag();
                        refTag.setDictItemValue(tag);
                        refTag.setCrossId(crossing.getId());
                        refTag.setDictCode(DictCodeEnums.ROAD_TAG.getDictCode());
                        return refTag;
                    })
                    .collect(Collectors.toList());

            // 输出结果
            refTagList.forEach(System.out::println);
            crossRefTagService.saveBatch(refTagList);
        }
        return Result.OK("添加成功！");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateByValidate(CrossDTO crossDTO) {
        QueryWrapper<TCrossing> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", crossDTO.getCode());
        queryWrapper.ne("id", crossDTO.getId());
        List<TCrossing> exitsList = crossingMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(exitsList)) {
            return Result.error("路口编号'" + crossDTO.getCode() + "'已存在!" );
        }

        //处理道路
        List<String> roadIdList = crossDTO.getRoadIds();
        String roadIds = String.join(",", roadIdList);

        List<TRoad> roadList = roadService.list(new QueryWrapper<TRoad>().in("id", roadIdList));
        String roadName = roadList.stream()
                .map(road -> road.getRoadName())         // 提取每个TRoad对象的name属性
                .filter(Objects::nonNull)    // 过滤掉可能存在的null值
                .collect(Collectors.joining(",")); // 用逗号连接成字符串

        TCrossing crossing = crossingMapper.selectById(crossDTO.getId());
        BeanUtils.copyProperties(crossDTO, crossing);
        crossing.setRoadId(roadIds);
        crossing.setRoadName(roadName);
        crossingMapper.updateById(crossing);

        //处理路口和道路关系
        //先删除
        QueryWrapper oldRefQueryWrapper = new QueryWrapper<TRoadRefCross>().eq("cross_id", crossing.getId());
        roadRefCrossService.remove(oldRefQueryWrapper);

        if (CollectionUtils.isNotEmpty(roadIdList)) {
            // 创建TCrossingRefTag集合
            List<TRoadRefCross> refTagList = roadIdList.stream()
                    .map(roadId -> {
                        TRoadRefCross refCross = new TRoadRefCross();
                        refCross.setRoadId(roadId);
                        refCross.setCrossId(crossing.getId());
                        return refCross;
                    })
                    .collect(Collectors.toList());
            roadRefCrossService.saveBatch(refTagList);
        }

        //处理路口标签关系
        String tags = crossing.getCrossTag();
        List<String> tagList = Arrays.asList(tags.split(","));
        if (CollectionUtils.isNotEmpty(tagList)) {
            //先删除
            crossRefTagService.remove(new QueryWrapper<TCrossingRefTag>().eq("cross_id", crossing.getId()));
            // 创建TCrossingRefTag集合
            List<TCrossingRefTag> refTagList = tagList.stream()
                    .map(tag -> {
                        TCrossingRefTag refTag = new TCrossingRefTag();
                        refTag.setDictItemValue(tag);
                        refTag.setCrossId(crossing.getId());
                        refTag.setDictCode(DictCodeEnums.ROAD_TAG.getDictCode());
                        return refTag;
                    })
                    .collect(Collectors.toList());
            crossRefTagService.saveBatch(refTagList);
        }
        return Result.OK("修改成功！");
    }

    @Override
    public Result deleteById(String id) {
        crossingMapper.deleteById(id);
        return Result.OK("删除成功！");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteByIds(String ids) {
        List<String> crossIdList = Arrays.asList(ids.split(","));
        if (CollectionUtils.isNotEmpty(crossIdList)) {
            crossIdList.stream().forEach(crossId -> {
                crossRefTagService.remove(new QueryWrapper<TCrossingRefTag>().eq("cross_id", crossId));
            });
        }
        crossingMapper.deleteBatchIds(crossIdList);
        return Result.OK("批量删除成功!");
    }
}
